<template>
	<div class="game-container report-container">
		<div class="view-container dealer-container">
			<div class="params">
				<el-form ref="form" :inline="true" :model="queryData">
					<el-form-item
						:label="`${$t('member.merchant_id')}:`"
						prop="merchantId"
						:rules="[
							{
								required: false,
								message: $t('member.please_select_a_merchant'),
								trigger: 'change'
							}
						]"
					>
						<merchant-select
							v-model="queryData.merchantId"
							v-symbols
							:placeholder="$t('common.please_choose')"
							@change="selectMerchantHandle(merchantList)"
						></merchant-select>
					</el-form-item>
					<el-form-item>
						<el-button
							type="primary"
							:disabled="!queryData.merchantId"
							size="medium"
							@click="query"
						>
							{{ $t('common.search') }}
						</el-button>
					</el-form-item>
					<el-form-item
						v-if="isShow && hasPermission('104031')"
						:label="`${$t('member.active_status')}:`"
						style="margin-left:-5px"
					>
						<el-switch
							:value="activeStatus"
							:active-text="$t('common.open')"
							:inactive-text="$t('common.close')"
							:active-value="1"
							:inactive-value="0"
							@change="handleSwitch($event)"
						></el-switch>
					</el-form-item>
				</el-form>
			</div>
			<div v-if="isShow" class="content">
				<el-form
					ref="tableForm"
					:inline="false"
					size="normal"
					:model="{ dataList }"
				>
					<el-table
						v-loading="loading"
						element-loading-spinner="el-icon-loading"
						border
						size="mini"
						class="small-size-table"
						:data="dataList"
						style="width: 100%"
						:header-cell-style="getRowClass"
						highlight-current-row
					>
						<el-table-column
							align="center"
							:label="$t('common.vip_level')"
							prop="vipSerialNum"
							width="120"
						>
							<template slot-scope="scope">
								{{
									(scope.row.vipSerialNum &&
										'VIP' + scope.row.vipSerialNum) ||
										'-'
								}}
							</template>
						</el-table-column>
						<el-table-column
							prop="lowestTransferQuota"
							align="center"
							label="最低转账额度"
						>
							<template v-slot:header>
								<span class="other-class">
									{{ $t('member.lowest_transfer_quota') }}({{
										handleCurrency(currency, true)
									}})
								</span>
							</template>
							<template slot-scope="scope">
								<span>
									<el-input-number
										v-model="scope.row.lowestTransferQuota"
										:disabled="scope.row.state === 0"
										size="medium"
										:max="999999999999"
										:min="0"
										:precision="0"
										:placeholder="$t('common.please_enter')"
										style="width: auto"
										@blur="
											checkTransferValue(
												scope.row,
												'lowestTransferQuota'
											)
										"
									></el-input-number>
								</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="bonusRatio"
							align="center"
							:label="`${$t('member.bonus_ratio')}`"
						>
							<template slot="header" slot-scope="scope">
								<el-popover
									placement="top-start"
									:title="`${$t('member.tips')}`"
									width="280"
									trigger="hover"
								>
									<div v-if="!scope.row">
										<div>
											{{ $t('member.bonus_ratio_tips') }}
										</div>
									</div>
									<div
										slot="reference"
										class="el-icon-question"
									>
										<span class="other-class">
											{{ $t('member.bonus_ratio') }}
										</span>
									</div>
								</el-popover>
							</template>
							<template slot-scope="scope">
								<div>
									<span>
										<el-input-number
											v-model.number="
												scope.row.bonusRatio
											"
											size="medium"
											:disabled="scope.row.state === 0"
											maxlength="5"
											:max="100"
											:precision="0"
											:min="0"
											:placeholder="
												$t('common.please_enter')
											"
											style="width: 85%"
											@blur="
												checkTransferValue(
													scope.row,
													'bonusRatio'
												)
											"
										></el-input-number>
									</span>
									<span>%</span>
								</div>
							</template>
						</el-table-column>
						<el-table-column
							prop="highestBonus"
							align="center"
							label="最高奖金"
						>
							<template v-slot:header>
								<div>
									<span class="other-class">
										{{ $t('member.highest_bonus') }}({{
											handleCurrency(currency, true)
										}})
									</span>
								</div>
							</template>

							<template slot-scope="scope">
								<span>
									<el-input-number
										v-model="scope.row.highestBonus"
										size="medium"
										:disabled="scope.row.state === 0"
										:max="999999999999"
										:precision="0"
										:min="0"
										:placeholder="$t('common.please_enter')"
										style="width: auto"
										@blur="
											checkTransferValue(
												scope.row,
												'highestBonus'
											)
										"
									></el-input-number>
								</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="waterMultiple"
							align="center"
							:label="`${$t('member.water_multiple')}`"
						>
							<template slot-scope="scope">
								<span>
									<el-input-number
										v-model="scope.row.waterMultiple"
										size="medium"
										:disabled="scope.row.state === 0"
										:max="99"
										:precision="0"
										:min="0"
										:placeholder="$t('common.please_enter')"
										style="width: auto"
										@blur="
											checkTransferValue(
												scope.row,
												'waterMultiple'
											)
										"
									></el-input-number>
								</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="participateNum"
							align="center"
							:label="`${$t('member.participate_num')}`"
						>
							<template slot-scope="scope">
								<span>
									<el-select
										v-model="scope.row.participateNum"
										:disabled="scope.row.state === 0"
										:placeholder="
											$t('common.please_choose')
										"
										style="width: auto"
									>
										<el-option
											v-for="item in participateTypeArr"
											:key="item.code"
											:label="item.description"
											:value="item.code * 1"
										></el-option>
									</el-select>
								</span>
							</template>
						</el-table-column>
						<el-table-column
							align="center"
							:label="`${$t('member.participate_venue')}`"
							prop="participateVenue"
							width="300"
						>
							<template slot-scope="scope">
								<el-form-item
									:prop="
										`dataList.${
											scope.$index
										}.participateVenue`
									"
									:rules="[
										{
											required: true,
											message: $t(
												'member.please_choose_venue'
											),
											trigger: 'change'
										}
									]"
									class="venue-select"
								>
									<el-select
										v-model="scope.row.participateVenue"
										multiple
										style="width:100%"
										:placeholder="
											$t('member.please_choose_venue')
										"
										:disabled="scope.row.state === 0"
										value-key="id"
										collapse-tags
									>
										<el-option
											v-for="item in bwVenueList"
											:key="item.venueCode"
											:label="item.venueName"
											:value="item.venueCode"
										></el-option>
									</el-select>
								</el-form-item>
							</template>
						</el-table-column>
					</el-table>
				</el-form>
			</div>
			<div v-if="isShow" class="btn_footer">
				<el-button
					v-if="hasPermission('104032')"
					type="primary"
					icon="el-icon-search"
					size="medium"
					:disabled="loading"
					@click="saveData"
				>
					{{ $t('common.save') }}
				</el-button>
				<el-button
					v-if="hasPermission('104033')"
					icon="el-icon-refresh-left"
					size="medium"
					@click="resetData"
				>
					{{ $t('member.restore_last_onfiguration') }}
				</el-button>
			</div>
		</div>
	</div>
</template>

<script>
import list from '@/mixins/list'
import { queryMerchantVenueListApi } from '@/api/merchant/merchant-config/venue-config'
import { mapGetters } from 'vuex'
import { routerNames } from '@/utils/consts'

export default {
	name: routerNames.vipDiscountConfig,
	mixins: [list],
	data() {
		this.saveData = this.throttle(this.saveData, 1000)
		this.resetData = this.throttle(this.resetData, 1000)
		return {
			bwVenueList: [],
			dataList: [],
			queryData: {
				merchantId: ''
			},
			switch: '',
			isShow: false,
			currency: '',
			gameVenueList: [],
			loading: false,
			activeStatus: 0,
			merchantCurrency: []
		}
	},
	computed: {
		...mapGetters(['merchantInfo']),

		participateTypeArr() {
			return this.globalDics.participateType || []
		}
	},
	created() {
		if (!this.$store.getters.isZk) {
			this.queryData.merchantId = this.$store.getters.merchantInfo.id
			this.getBwVenueList()
			this.currency = this.$store.getters.merchantInfo.currency
		}
	},
	methods: {
		// 获取场馆列表
		getBwVenueList() {
			queryMerchantVenueListApi({
				merchantId: this.queryData.merchantId
			}).then((res) => {
				this.bwVenueList = res.data[0]?.list || []
				if (!res.data.length) {
					this.isShow = true
					return
				}
				this.getmemberVipPromotionListAPI()
			})
		},
		checkTransferValue(row, type) {
			if (!row[type]) {
				row[type] = 0
			}
		},
		selectMerchantHandle(val) {
			this.merchantCurrency = val
		},
		query() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					for (let i = 0; i < this.merchantCurrency.length; i++) {
						const ele = this.merchantCurrency[i]
						if (this.queryData.merchantId === ele.id) {
							this.currency = ele.currency
						}
					}
					this.getBwVenueList()
				}
			})
		},
		getmemberVipPromotionListAPI(val) {
			this.dataList = []
			this.$api
				.memberVipPromotionListAPI({
					merchantId: this.queryData.merchantId
				})
				.then((res) => {
					this.loading = false
					this.isShow = true

					const arr = res.data.map((item) => {
						const num = {}
						item.bonusRatio = this.decimalToMul(item.bonusRatio)
						const participateVenueList =
							item.participateVenue?.split(',') || []
						const bwVenueEleList = []
						for (let i = 0; i < this.bwVenueList.length; i++) {
							const element = this.bwVenueList[i].venueCode
							for (
								let j = 0;
								j < participateVenueList.length;
								j++
							) {
								const ele = participateVenueList[j]
								if (element === ele) {
									bwVenueEleList.push(element)
								}
							}
						}
						item.participateVenue
							? (num.participateVenue = bwVenueEleList)
							: (num.participateVenue = [])
						return Object.assign(item, num)
					})
					this.dataList = arr || []
					this.activeStatus = arr[0].state
				})
				.catch(() => {
					this.loading = false
				})
		},
		saveData() {
			this.$refs.tableForm.validate((valid) => {
				if (valid) {
					this.loading = true
					const memberVipPromotionParams = this.dataList.map(
						(item) => {
							return {
								id: item.id,
								bonusRatio: this.decimalToDiv(item.bonusRatio),
								highestBonus: item.highestBonus,
								merchantId: this.queryData.merchantId,
								lowestTransferQuota: item.lowestTransferQuota,
								participateNum: item.participateNum,
								participateVenue: item.participateVenue.join(
									','
								),
								vipSerialNum: item.vipSerialNum,
								waterMultiple: item.waterMultiple
							}
						}
					)
					this.$api
						.memberVipPromotionUpdateAPI(memberVipPromotionParams)
						.then(() => {
							this.loading = false

							this.$message({
								message: this.$t('common.save_success'),
								type: 'success'
							})

							this.loadData()
						})
						.catch(() => {
							this.loading = false
						})
				}
			})
		},
		resetData() {
			const { decimalToMul } = this
			this.$api
				.memberVipPromotionRollbackAPI({
					merchantId: this.queryData.merchantId
				})
				.then((res) => {
					const arr =
						res?.data.length &&
						res?.data.map((item) => {
							const num = {}
							item.bonusRatio = decimalToMul(item.bonusRatio)
							item.participateVenue
								? (num.participateVenue = item.participateVenue.split(
										','
								  ))
								: (num.participateVenue = [])
							return Object.assign(item, num)
						})
					this.dataList = arr || []
					this.$message({
						message: this.$t('common.reset_succeeded'),
						type: 'success'
					})
				})
				.catch(() => {})
		},
		handleSwitch(val) {
			if (this.queryData.merchantId === undefined) {
				return this.$message.warning(
					this.$t('member.please_select_merchant1')
				)
			}
			const params = {
				merchantId: this.queryData.merchantId,
				state: val
			}
			if (val === 1) {
				this.switch = this.$t('member.confirm_to_open_vip')
			} else {
				this.switch = this.$t('member.confirm_to_close_vip')
			}
			this.$confirm(
				`<strong>${
					this.switch
				}？</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
					'member.warning_tips'
				)}</span>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.$api
						.memberVipPromotionUpdateStateAPI(params)
						.then(() => {
							this.$message.success(
								this.$t('common.action_success')
							)
							this.getmemberVipPromotionListAPI()
						})
				})
				.catch(() => {})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}

::v-deep .el-input-number__decrease,
::v-deep .el-input-number__increase {
	display: none;
}
.btn_footer {
	text-align: center;
	margin-top: 50px;
}
::v-deep .el-icon-question:after {
	content: '\E7A4';
	font-size: 25px;
}
::v-deep .el-icon-question::before {
	content: '';
}

::v-deep .venue-select .el-form-item__error {
	margin-left: 40px;
}
</style>
